package topofstack.networkserverutils.mail;

import java.util.Enumeration;
import java.util.Properties;

import javax.mail.FetchProfile;
import javax.mail.Folder;
import javax.mail.Header;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;

import com.sun.mail.pop3.POP3SSLStore;

public class ReceiveMailPOP {

	private Session session = null;
	private Store store = null;
	private String username, password;
	private Folder folder;
	private String host;
	private String port;

	public ReceiveMailPOP(String host, String port, String username,
			String password) {
		this.host = host;
		this.port = port;
		this.username = username;
		this.password = password;
	}

	public void connect() throws Exception {

		String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

		Properties pop3Props = new Properties();

		pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
		pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
		pop3Props.setProperty("mail.pop3.port", port);
		pop3Props.setProperty("mail.pop3.socketFactory.port", port);

		URLName url = new URLName("pop3", host, Integer.parseInt(port), "",
				username, password);

		session = Session.getInstance(pop3Props, null);
		store = new POP3SSLStore(session, url);
		store.connect();

	}

	public void openFolder(String folderName) throws Exception {

		// Open the Folder
		folder = store.getDefaultFolder();
		folder = folder.getFolder(folderName);

		if (folder == null) {
			throw new Exception("Invalid folder");
		}

		// try to open read/write and if that fails try read-only
		try {
			folder.open(Folder.READ_WRITE);
		} catch (MessagingException ex) {
			folder.open(Folder.READ_ONLY);
		}
	}

	public void closeFolder() throws Exception {
		folder.close(false);
	}

	public int getMessageCount() throws Exception {
		return folder.getMessageCount();
	}

	public int getNewMessageCount() throws Exception {
		return folder.getNewMessageCount();
	}

	public void disconnect() throws Exception {
		store.close();
	}

	public String getTime() throws Exception {

		// Attributes & Flags for all messages ..
		Message[] messages = folder.getMessages();
		if (messages.length == 0)
			return "-1";

		// Use a suitable FetchProfile
		FetchProfile fp = new FetchProfile();
		fp.add(FetchProfile.Item.ENVELOPE);
		folder.fetch(messages, fp);

		Message message = messages[messages.length - 1];

		Enumeration headers = message.getAllHeaders();
		String result = "";
		while (headers.hasMoreElements()) {
			Header h = (Header) headers.nextElement();
			result += String.format("%8s:\t%s\n", h.getName().trim(), h.getValue().trim());
			//Log.d("Header", h.getName() + ": " + h.getValue());
		}

		/*Log.d("Time diff", sentTime.toString() + "-" + receivedTime.toString());
		long deliveryTime = receivedTime.getTime() - sentTime.getTime();

		return new MailInfo(deliveryTime, sentTime.toString(),
				receivedTime.toString());*/
		return result;
	}

	public String get() {

		try {
			connect();
			openFolder("INBOX");

			return getTime();

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				closeFolder();
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}
	}
}
